var icdev = 0; //设备句柄
var lock = new Lock()
var data = undefined
var resetData = undefined
var uid = undefined
var msg = {} ;
var layer = layui.layer
var form = layui.form
var status = 0 // 0 未复位   1 已复位
var reader = getReader(async function(){
    // 连接USB读卡器
    try {
        reader.connectUsb(); //连接usb设备
        await lock.wait()
    } catch (e) {
        msg.value = msg.value + e.Message + "\n";
    }
}); //获取reader对象, getReader会自动连接ReaderService服务
if (reader == null) {
    alert('您的浏览器不支持读写器服务.');
}

// 设置回调
reader.onResult(function (ret) {
    data = ret
    console.log("返回："+data.resultData)
    lock.notify(data)
    //执行成功
    if (ret.result == 0) {
        switch (ret.functionId) {
            case READER_CMD._reader_server_connect:
                break;
            case READER_CMD._reader_cmd_connect:
                icdev = parseInt(ret.resultData); //连接成功后, resultData 为设备句柄
                msg.value = msg.value + "读写器连接成功.\n";
                break;
            case READER_CMD._reader_cmd_disconnect:
                msg.value = msg.value + "读写器断开连接成功.\n";
                break;
            case READER_CMD._reader_cmd_beep:
                msg.value = msg.value + "读写器鸣响成功.\n";
                break;
            case READER_CMD._reader_cmd_rf_card:
            case READER_CMD._reader_cmd_rf_card_b:
                msg.value = msg.value + "寻卡成功, 卡片序列号: " + ret.resultData + "\n";
                break;
            case READER_CMD._reader_cmd_c_cpu_reset:
                msg.value = msg.value + "非接触式 TypeA CPU 卡复位成功. 复位信息: " + ret.resultData + "\n";
                break;
            case READER_CMD._reader_cmd_c_cpu_reset_b:
                msg.value = msg.value + "非接触式 TypeB CPU 卡复位成功.\n";
                break;
            case READER_CMD._reader_cmd_rf_halt:
            case READER_CMD._reader_cmd_rf_halt_b:
                msg.value = msg.value + "终止卡片操作成功.\n";
                break;
            case READER_CMD._reader_cmd_uc_auth_key:
                msg.value = msg.value + "Ultralight C 校验密码成功.\n";
                break;
            case READER_CMD._reader_cmd_uev_auth_key:
                msg.value = msg.value + "Ultralight EV 校验密码成功.\n";
                break;
            case READER_CMD._reader_cmd_u_read:
                msg.value = msg.value + "Ultralight / Ultralight C 读数据成功. 读取到的数据: " + ret.resultData + "\n";
                break;
            case READER_CMD._reader_cmd_u_write:
                msg.value = msg.value + "Ultralight / Ultralight C 写数据成功.\n";
                break;
            case READER_CMD._reader_cmd_uc_change_key:
                msg.value = msg.value + "更改  Ultralight C 密码成功.\n";
                break;
        }
    } else {
        //失败打印错误信息
        msg.value = msg.value + ret.resultData + "\n";
    }
    // console.log(data)
});

function Str2Bytes(str)

{

    var pos = 0;

    var len = str.length;

    if(len %2 != 0)

    {

        return null;

    }

    len /= 2;

    var hexA = new Array();

    for(var i=0; i<len; i++)

    {

        var s = str.substr(pos, 2);

        var v = parseInt(s, 16);

        hexA.push(v);

        pos += 2;

    }

    return hexA;

}

function UTF8ToStr(arr) {
    let val = ''
    arr.forEach(item => {
        if (item < 127) {
            val += String.fromCharCode(item)
        } else {
            val += '%' + item.toString(16).toUpperCase()
        }
    })
    try {
        return decodeURI(val)
    } catch (err) {
        return val
    }
}

// 定时寻卡
async function find_card(){
    try {
        reader.rfCard(icdev, 1);
        await lock.wait()
        uid = data.resultData
        console.log("卡号："+uid)
        if(uid != "请求失败。" && uid != "设备未连接。"){
            clearInterval(timer)
            status = 1
            cardNo = uid
            // 请求用户信息
            $.ajax({
                url: HOST+"cz/getStaffInfo?cardNo=" + cardNo
                , type: "get"
                ,beforeSend: function(request) {
                    request.setRequestHeader("token", layui.data('local_store').token);
                }
                , success: function (data) {
                    if (data.code == 1){
                        layer.msg("读取成功");
                        $("#staffId").val(data.data.staff.id);
                        $("#pin").val("");
                        $("#staffBalance").val(data.data.balance);
                        $("#ygName").val(data.data.staff.name);
                        var sex = data.data.staff.sex;
                        if(sex==1){
                            $("#nan").prop("checked",true);
                            form.render()
                        }else{
                            $("#nv").prop("checked",true);
                            form.render()
                        }
                        // if (sex == 1) {
                        //     $("input[name=sex][value='0']").prop("checked","false");
                        //     form.render();
                        // }else {
                        //     $("input[name=sex][value='0']").prop("checked","true");
                        //     form.render();
                        // }
                        $("#phone").val(data.data.staff.phone);
                        $("#bh").val(data.data.staff.bh);
                        $("#sfz").val(data.data.staff.sfz);
                        // $("#cls").val(data.data.staff.qiye.qyname);
                        $("#cardStatus").val(data.data.cardStatus);
                        form.render();
                    }else {
                        layer.msg("卡号不存在！");
                        return;
                    }
                }
            });
            $("#cardNo").val(uid);
            form.render()
        }else{
            return
        }
        reader.mifareCpuReset(icdev);
        await lock.wait()
        resetData = data.resultData
        // 查询卡内余额
        reader.mifareCpuTransmit(icdev , "00A40000021001")
        await lock.wait()
        if(checkRs() != undefined) {
            layer.msg(checkRs())
            return false
        }
        // reader.mifareCpuTransmit(icdev , "805C000204")
        // await lock.wait()
        // if(checkRs() != undefined) {
        //     layer.msg(checkRs())
        //     return false
        // }
        console.log("----------定时寻卡");
        console.log(data.resultData.substr(0 , data.resultData.length - 4))
        var arr = Str2Bytes(data.resultData.substr(0 , data.resultData.length - 4))
        console.log(arr)
        var num = (arr[0] & 0xff) << 24 | (arr[1] & 0xff) << 16 | (arr[2] & 0xff) << 8 | arr[3] & 0xff ;
        $("#card").val(num / 100)
        form.render()
        // var str = UTF8ToStr(arr)
        // console.log(str)
    } catch (e) {
        console.log(e)
        // msg.value = msg.value + e.Message + "\n";
    }
}

timer = setInterval(find_card , 1000)


function checkRs(){
    switch(data.resultData) {
        case "6200":
            return "警告 信息未提供"
        case "6281":
            return "警告 回送数据可能"
        case "6282":
            return "警告 文件长度小于Le"
        case "6283" :
            return "警告 选中的文件无效"
        case "6284":
            return "警告 FCI格式与P2指定的不符"
        case "6300":
            return "警告 鉴别失败"
        case "63C2":
            return "警告 校验失败（允许重试次数2）"
        case "63C1":
            return "警告 校验失败（允许重试次数1）"
        case "6400":
            return "状态标志位没有变"
        case "6581":
            return "内存失败"
        case "6700":
            return "长度错误"
        case "6882" :
            return "不支持安全报文"
        case "6981":
            return "命令与文件结构不相容，当前文件非所需文件"
        case "6982":
            return "操作条件（AC）不满足，没有校验PIN"
        case "6983":
            return "您的卡已被锁定"
        case "6984":
            return "随机数无效，引用的数据无效"
        case "6985":
            return "使用条件不满足"
        case "6986":
            return "不满足命令执行条件（不允许的命令，INS有错）"
        case "6987":
            return "MAC丢失"
        case "6988":
            return "MAC不正确"
        case "698D":
            return "保留"
        case "6A80":
            return "数据域参数不正确"
        case "6A81":
            return "功能不支持；创建不允许；目录无效；应用锁定"
        case "6A82":
            return "该文件未找到"
        case "6A83":
            return "该记录未找到"
        case "6A84":
            return "文件预留空间不足"
        case "6A86":
            return "P1或P2不正确"
        case "6A88":
            return "引用数据未找到"
        case "6B00":
            return "参数错误"
        case "6C":
            return "Le长度错误"
        case "6E00":
            return "不支持的类：CLA有错"
        case "6F00":
            return "数据无效"
        case "6F01" :
            return "连接中断"
        case "6D00":
            return "不支持的指令代码"
        case "9301":
            return "您的卡余额不足"
        case "9302":
            return "MAC2错误"
        case "9303":
            return "应用被永久锁定"
        case "9401":
            return "您的卡余额不足"
        case "9402":
            return "交易计数器达到最大值"
        case "9403":
            return "密钥索引不支持"
        case "9406":
            return "所需MAC不可用"
        case "6900":
            return "不能处理"
        case "6901":
            return "命令不接受（无效状态）"
        case "61":
            return "正常 需发GET RESPONSE命令"
        case "6600":
            return  "接收通讯超时"
        case "6601":
            return "接收字符奇偶错"
        case "6602":
            return "校验和不对"
        case "6603":
            return "警告 当前DF文件无FCI"
        case "6604":
            return "警告 当前DF下无SF或KF"
        case "6E81":
            return "卡片已离开"
        default:
            return undefined
    }
}